import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/db';
import { verifyToken } from '@/lib/auth';
import { cookies } from 'next/headers';
import { hashPassword } from '@/lib/auth';

export async function POST(request: NextRequest) {
    const token = cookies().get('token')?.value;
    const payload = token ? await verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // 检查用户角色是否为管理员
    if (payload.role !== 'Scrum Master') {
      return NextResponse.json({ error: '没有权限执行此操作' }, { status: 403 });
    }
  
    const { email } = await request.json();
  
    try {
      // 查找用户
      const user = await prisma.user.findUnique({
        where: { email },
      });
  
      if (!user) {
        return NextResponse.json({ error: '用户不存在' }, { status: 404 });
      }
  
      // 更新密码
      const updatedUser = await prisma.user.update({
        where: { email },
        data: {
          password: await hashPassword("123456")
        },
      });
  
      return NextResponse.json({ message: '密码重置成功' }, { status: 200 });
    } catch (error) {
      console.log("重置密码失败:", error)
      return NextResponse.json({ error: '重置密码失败' }, { status: 500 });
    }
}
